public enum VendingMachineState {
    IDLE, SELECTING, PAYING
}

定义状态接口和具体的状态类：
public interface State {
    void handle(VendingMachineContext context);
}

public class IdleState implements State {
    @Override
    public void handle(VendingMachineContext context) {
        System.out.println("Machine is idle. Waiting for user to select an item.");
        // 当用户选择商品时，状态转换为SELECTING
        context.setState(VendingMachineState.SELECTING);
    }
}
管理状态的切换
public class SelectingState implements State {
    @Override
    public void handle(VendingMachineContext context) {
        System.out.println("User is selecting an item. Please make your selection.");
        // 假设用户已经选择了商品，状态转换为PAYING
        context.setState(VendingMachineState.PAYING);
    }
}

public class PayingState implements State {
    @Override
    public void handle(VendingMachineContext context) {
        System.out.println("User is paying for the selected item. Please insert coins.");
        // 假设用户已经完成支付，状态转换回IDLE
        context.setState(VendingMachineState.IDLE);
    }
}

public class VendingMachineContext {
    private VendingMachineState state;
    private State currentState;

    public VendingMachineContext() {
        this.state = VendingMachineState.IDLE;
        switchState();
    }

    public void setState(VendingMachineState newState) {
        this.state = newState;
        switchState();
    }

    private void switchState() {
        switch (state) {
            case IDLE:
                currentState = new IdleState();
                break;
            case SELECTING:
                currentState = new SelectingState();
                break;
            case PAYING:
                currentState = new PayingState();
                break;
            default:
                throw new IllegalArgumentException("Invalid state: " + state);
        }
        currentState.handle(this); // 处理当前状态
    }
}
主函数
public class Main {
    public static void main(String[] args) {
        VendingMachineContext vendingMachine = new VendingMachineContext();
        // 模拟用户操作，这里只是为了演示，实际应用中状态的变化应该由用户的实际操作触发
        vendingMachine.setState(VendingMachineState.IDLE); // 用户离开后机器回到初始状态
    }
}
